import pymysql
from collections import OrderedDict
from app.services.business.gaolu_diagnose import bengzuoguan_process, jianfeng_process, lose_score
from app.models.po.gaolu.gaolu_diagnose_rule import GaoLuDiagnoseRulePO
from app.models.po.gaolu.gaolu_diagnose_data import GaoLuDiagnoseDataPO, GaoLuDiagnoseScorePO, GaoLuDiagnoseCountPO
import logging as log
import json
from app.exts import mysql_pool
from app.services.business.gaolu_diagnose.ind import ind_cls_dict
from app.services.business.gaolu_diagnose.ind.abstract_ind import AbstractInd
from app.utils import date_util


def run():
    from typing import List
    from app.database import convert

    from datetime import datetime, timedelta
    from app.exts import db, influxdb
    from app import get_app
    app = get_app()
    rules: List[GaoLuDiagnoseRulePO] = convert.query(GaoLuDiagnoseRulePO, is_deleted=0).all()
    # engine = db.get_engine(app, "cg")
    influxdb_client = influxdb.get_client()
    conn, cursor = mysql_pool.connect()
    result_dict: dict = run_internal(cursor, influxdb_client, rules)
    mysql_pool.connect_close(conn, cursor)

    result_dict = {k: float(result_dict.get(k,0)) for k in result_dict.keys()}

    now = date_util.get_start_of_day(datetime.now())
    diagnose_data = convert.query(GaoLuDiagnoseDataPO, GaoLuDiagnoseDataPO.date_time == now).first()

    if diagnose_data is None:
        diagnose_data = GaoLuDiagnoseDataPO()
        diagnose_data.date_time = now
        diagnose_data.__dict__.update(result_dict)
        convert.add_one(diagnose_data)
    else:
        convert.update_model(diagnose_data, result_dict)

    score_dict = lose_score.cal(rules, result_dict)
    item_group = {}
    zf = 0  # 总分
    for key, item in score_dict.items():
        score = item_group.get(item['scope'], 0)
        score = score + item['score']
        item_group[item['scope']] = score
        item_group[item['key']] = item['score']
        zf = zf + item['score']

    diagnose_score = convert.query(GaoLuDiagnoseScorePO, GaoLuDiagnoseScorePO.date_time == now).first()
    if diagnose_score is None:
        rule_id = rules[0].rule_group_id
        diagnose_score = GaoLuDiagnoseScorePO()
        diagnose_score.date_time = now
        diagnose_score.rule_id = rule_id
        diagnose_score.__dict__.update(item_group)
        diagnose_score.rule_id
        diagnose_score.zf = zf
        convert.add_one(diagnose_score)
    else:
        item_group['zf'] = zf
        convert.update_model(diagnose_score, item_group)

    rule_count_dict = {}
    group_count_dict = {}
    for rule in rules:
        value = result_dict[rule.name]
        rule_count_dict[rule.name] = 0
        if rule.lower is not None and value < rule.lower:
            rule_count_dict[rule.name] = 1
        if rule.upper is not None and value > rule.upper:
            rule_count_dict[rule.name] = 1
    for rule in rules:
        count = group_count_dict.get(rule.scope, 0)
        count = count + rule_count_dict[rule.name]
        group_count_dict[rule.scope] = count
    rule_count_dict.update(group_count_dict)

    diagnose_count = convert.query(GaoLuDiagnoseCountPO, GaoLuDiagnoseCountPO.date_time == now).first()
    if diagnose_count is None:
        rule_id = rules[0].rule_group_id
        diagnose_count = GaoLuDiagnoseCountPO()
        diagnose_count.date_time = now
        diagnose_count.rule_id = rule_id
        diagnose_count.__dict__.update(rule_count_dict)
        convert.add_one(diagnose_count)
    else:
        convert.update_model(diagnose_count, rule_count_dict)


def get_influx_result(result_set, key):
    if len(result_set) > 0:
        return result_set[0][0][key]


def devide(v1, v2):
    if v1 is None: return 0
    if v2 is None or v2 == 0: return 0
    return v1 / v2


def run_internal(mysql_cursor, influxdb_client, rules):
    # results: List[GaoLuDiagnose] = convert.query(GaoLuDiagnose).all()
    from datetime import datetime, timedelta
    import numpy as np

    result_dict = {}

    date_start = date_util.dt_to_str(date_util.get_start_of_day(datetime.now() - timedelta(days=1)), '%Y-%m-%d')

    dt_start_tz = date_util.dt_to_str(date_util.get_start_of_day(datetime.now()) - timedelta(hours=16),
                                      '%Y-%m-%dT%H:%M:%SZ')
    dt_end_tz = date_util.dt_to_str(date_util.get_start_of_day(datetime.now()) + timedelta(hours=8),
                                    '%Y-%m-%dT%H:%M:%SZ')

    dt_start_hour_tz = date_util.dt_to_str(date_util.get_start_of_hour(datetime.now()) + timedelta(hours=8),
                                           '%Y-%m-%dT%H:%M:%SZ')
    dt_end_hour_tz = date_util.dt_to_str(date_util.get_next_of_hour(datetime.now()) + timedelta(hours=8),
                                         '%Y-%m-%dT%H:%M:%SZ')

    params = dict(dt_start=date_start,
                  dt_start_tz=dt_start_tz,
                  dt_end_tz=dt_end_tz,
                  dt_start_hour_tz=dt_start_hour_tz,
                  dt_end_hour_tz=dt_end_hour_tz
                  )

    for rule in rules:
        name = rule.name

        if name in ind_cls_dict.keys():
            cls = ind_cls_dict[name]
            instance: AbstractInd = cls(influxdb_client, params, mysql_pool)
            log.info("debug gaolu diagnose {}".format(name))
            value = instance.get_result()
            result_dict[name] = value
            continue

        if name == 'CG_LT_GL_GL04_RjianfengCi':
            value = jianfeng_process.jianfeng_ci(influxdb_client, dt_start_tz, dt_end_tz)
            result_dict[name] = value
            continue
        if name == 'CG_LT_GL_GL04_RbengzuoguanCi':
            value = bengzuoguan_process.bengzuoguan_ci(influxdb_client, dt_start_tz, dt_end_tz)
            result_dict[name] = value
            continue

        config = configs.get(name)
        sql = config.get("sql")
        t = config.get("type")

        if t == 'mysql':
            if name == "CG_LT_GL_GL04_RMg_Al":
                mg_sql = sql['CG_LT_GL_GL04_RMg']
                al_sql = sql['CG_LT_GL_GL04_RAl']

                mysql_cursor.execute(mg_sql.format(date_start))
                mg_result = mysql_cursor.fetchone()['CG_LT_GL_GL04_RMg']
                # print("CG_LT_GL_GL04_RMg", mg_result)
                mysql_cursor.execute(al_sql.format(date_start))
                al_result = mysql_cursor.fetchone()['CG_LT_GL_GL04_RAl']
                # print("CG_LT_GL_GL04_RAl", al_result)
                print(mg_result, al_result)
                result_dict[name] = devide(mg_result, al_result)
            else:
                mysql_cursor.execute(sql.format(date_start))
                r = mysql_cursor.fetchone()[name]
                r = 0 if r is None else r
                result_dict[name] = r
        if t == 'influxdb':

            if isinstance(sql, dict):
                results = []
                for sub_name, sql_str in sql.items():
                    result_set = list(influxdb_client.query(sql_str.format(dt_start_tz, dt_end_tz)))
                    results.append(get_influx_result(result_set, sub_name))
                result_dict[name] = np.mean(results)
            else:
                result_set = list(influxdb_client.query(sql.format(dt_start_tz, dt_end_tz)))
                result_dict[name] = get_influx_result(result_set, name)

    return result_dict


configs = OrderedDict(
    CG_LT_GL_GL04_Rliaopi=dict(sql="""
        select 
        SUM(fbatchhour) as CG_LT_GL_GL04_Rliaopi
        FROM
        syn_tq_rshangliaoqk where  fdate='{}'
""", type="mysql"),
    CG_LT_GL_GL04_RRLB=dict(sql="""
        select 
        ROUND(AVG(fcokerate),0)+ROUND(AVG(fcoalrate),0) as CG_LT_GL_GL04_RRLB
        FROM
        syn_tq_rshangliaoqk where fdate='{}'
""", type="mysql"),
    CG_LT_GL_GL04_Rcokerate=dict(sql="""
        select 
        ROUND(AVG(fcoalrate),0) as CG_LT_GL_GL04_Rcokerate
        FROM
        syn_tq_rshangliaoqk where fdate='{}'
""", type="mysql"),
    CG_LT_GL_GL04_RLFLL=dict(sql="""
         SELECT mean(value) AS CG_LT_GL_GL04_RLFLL  FROM  "CG_LT_GL_GL04_LFLL"
         where time > '{}' and time < '{}'
         """, type="influxdb"),
    CG_LT_GL_GL04_RFYLL=dict(sql="""
        SELECT mean(value) AS CG_LT_GL_GL04_RFYLL    FROM "CG_LT_GL_GL04_FYLL" 
        where time > '{}' and time < '{}'
    """, type="influxdb"),
    CG_LT_GL_GL04_RTQXZS=dict(sql="""
        SELECT mean(value) AS CG_LT_GL_GL04_RTQXZS    FROM "CG_LT_GL_GL04_TQXZS" 
        where time > '{}' and time < '{}'
    """, type="influxdb"),
    CG_LT_GL_GL04_RSBYCZB=dict(sql="""
        SELECT mean(value) AS CG_LT_GL_GL04_RSBYCZB    FROM "CG_LT_GL_GL04_SBYCZB"
        where time > '{}' and time < '{}'
    """, type="influxdb"),
    CG_LT_GL_GL04_RXBYCZB=dict(sql="""
        SELECT mean(value) AS CG_LT_GL_GL04_RXBYCZB    FROM "CG_LT_GL_GL04_XBYCZB"
        where time > '{}' and time < '{}'
    """, type="influxdb"),
    CG_LT_GL_GL04_RLLRSWD=dict(sql="""
        SELECT mean(value) AS CG_LT_GL_GL04_RLLRSWD    FROM "CG_LT_GL_GL04_LLRSWD" 
        where time > '{}' and time < '{}'
""", type="influxdb"),
    CG_LT_GL_GL04_RGFDNKG=dict(sql="""
        SELECT mean(value) AS CG_LT_GL_GL04_RGFDNKG    FROM "CG_LT_GL_GL04_GFDNKG" 
        where time > '{}' and time < '{}'
""", type="influxdb"),
    CG_LT_GL_GL04_RLDWD=dict(sql=dict(
        CG_LT_GL_GL04_DWXN="""SELECT mean(value) AS CG_LT_GL_GL04_DWXN  FROM "CG_LT_GL_GL04_DWXN" where time > '{}' and time < '{}'""",
        CG_LT_GL_GL04_DWDB="""SELECT mean(value) AS CG_LT_GL_GL04_DWDB  FROM "CG_LT_GL_GL04_DWDB" where time > '{}' and time < '{}'""",
        CG_LT_GL_GL04_DWXB="""SELECT mean(value) AS CG_LT_GL_GL04_DWXB  FROM "CG_LT_GL_GL04_DWXB" where time > '{}' and time < '{}'""",
        CG_LT_GL_GL04_DWDN="""SELECT mean(value) AS CG_LT_GL_GL04_DWDN  FROM "CG_LT_GL_GL04_DWDN" where time > '{}' and time < '{}'"""),
        type="influxdb"
    ),
    CG_LT_GL_GL04_RRFH=dict(sql="""
        SELECT mean(value) AS CG_LT_GL_GL04_RRFH    FROM "CG_LT_GL_GL04_RFH"
        where time > '{}' and time < '{}'
    """, type="influxdb"),
    CG_LT_GL_GL04_RFZWD=dict(sql="""
        SELECT mean(value) AS CG_LT_GL_GL04_RFZWD    FROM "CG_LT_GL_GL04_FZWD" 
        where time > '{}' and time < '{}'
""", type='influxdb'),
    CG_LT_GL_GL04_RchutieCi=dict(sql="""
        SELECT 
        COUNT(fnumber)  as CG_LT_GL_GL04_RchutieCi
        from syn_tq_rgaoluchutie
        where fdate = '{}'
""", type="mysql"),
    CG_LT_GL_GL04_Rtswd=dict(sql="""
        SELECT 
        round(AVG(ftswd),0) as CG_LT_GL_GL04_Rtswd 
        from syn_tq_rgaoluchutie
        where fdate  ='{}'
""", type="mysql"),
    CG_LT_GL_GL04_RSi_Ti=dict(sql="""
select round(avg(jyh.jyjg),4) as CG_LT_GL_GL04_RSi_Ti from 
syn_tq_rgaoluchutie,(select jyh.*,jyt.ph 
from syn_zl_zl_jyh as jyh ,syn_zl_zl_jyt as jyt 
where  jyh.jcxmbm='01058' and jyh.zfbz='0' 
and jyt.wlbm = '60110101' 
and SUBSTRING(jyt.ph, 3, 1) = '4' 
and  jyt.jytid = jyh.jytid 
and jyh.jyjg NOT LIKE '%#%' 
and jyh.jysj > DATE_SUB(CURDATE(), INTERVAL 1 WEEK)) as jyh 
where  SUBSTRING(jyh.ph,1,7) = concat(SUBSTRING(syn_tq_rgaoluchutie.fdate,3,2),'4',syn_tq_rgaoluchutie.fnumber) and syn_tq_rgaoluchutie.fdatetime > '{}'
""", type="mysql"),
    CG_LT_GL_GL04_RAl=dict(sql="""
select round(avg(jyh.jyjg),4) as CG_LT_GL_GL04_RAl from 
syn_tq_rgaoluchutie,(select jyh.*,jyt.ph 
from syn_zl_zl_jyh as jyh ,syn_zl_zl_jyt as jyt 
where  jyh.jcxmbm='01052' and jyh.zfbz='0' 
and jyt.wlbm = 'ZJ003' 
and SUBSTRING(jyt.ph, 4, 1) = '4' 
and  jyt.jytid = jyh.jytid 
and jyh.jyjg NOT LIKE '%#%' 
and jyh.jysj > DATE_SUB(CURDATE(), INTERVAL 1 WEEK)) as jyh 
where  SUBSTRING(jyh.ph,2,7) = concat(SUBSTRING(syn_tq_rgaoluchutie.fdate,3,2),'4',syn_tq_rgaoluchutie.fnumber) and syn_tq_rgaoluchutie.fdatetime > '{}'
""", type="mysql"),
    CG_LT_GL_GL04_RMg_Al=dict(sql=dict(
        CG_LT_GL_GL04_RMg="""
select round(avg(jyh.jyjg),4) as CG_LT_GL_GL04_RMg from 
syn_tq_rgaoluchutie,(select jyh.*,jyt.ph 
from syn_zl_zl_jyh as jyh ,syn_zl_zl_jyt as jyt 
where  jyh.jcxmbm='01013' and jyh.zfbz='0' 
and jyt.wlbm = 'ZJ003' 
and SUBSTRING(jyt.ph, 4, 1) = '4' 
and  jyt.jytid = jyh.jytid 
and jyh.jyjg NOT LIKE '%#%' 
and jyh.jysj > DATE_SUB(CURDATE(), INTERVAL 1 WEEK)) as jyh 
where  SUBSTRING(jyh.ph,2,7) = concat(SUBSTRING(syn_tq_rgaoluchutie.fdate,3,2),'4',syn_tq_rgaoluchutie.fnumber) and syn_tq_rgaoluchutie.fdatetime > '{}'
""", CG_LT_GL_GL04_RAl="""
select round(avg(jyh.jyjg),4) as CG_LT_GL_GL04_RAl from 
syn_tq_rgaoluchutie,(select jyh.*,jyt.ph 
from syn_zl_zl_jyh as jyh ,syn_zl_zl_jyt as jyt 
where  jyh.jcxmbm='01052' and jyh.zfbz='0' 
and jyt.wlbm = 'ZJ003' 
and SUBSTRING(jyt.ph, 4, 1) = '4' 
and  jyt.jytid = jyh.jytid 
and jyh.jyjg NOT LIKE '%#%' 
and jyh.jysj > DATE_SUB(CURDATE(), INTERVAL 1 WEEK)) as jyh 
where  SUBSTRING(jyh.ph,2,7) = concat(SUBSTRING(syn_tq_rgaoluchutie.fdate,3,2),'4',syn_tq_rgaoluchutie.fnumber) and syn_tq_rgaoluchutie.fdatetime > '{}'
"""
    ), type="mysql"),
    CG_LT_GL_GL04_R34m=dict(sql="""
SELECT mean(value) AS CG_LT_GL_GL04_R34m   FROM "CG_LT_GL_GL04_34800WDPJ" where time > '{}' and time < '{}'
""", type="influxdb"),
    CG_LT_GL_GL04_R26m=dict(sql="""
SELECT mean(value) AS CG_LT_GL_GL04_R26m   FROM "CG_LT_GL_GL04_26275WDPJ" where time > '{}' and time < '{}'
""", type="influxdb"),
    CG_LT_GL_GL04_R24m=dict(sql="""
SELECT mean(value) AS CG_LT_GL_GL04_R24m   FROM "CG_LT_GL_GL04_24145WDPJ" where time > '{}' and time < '{}'
""", type="influxdb"),
    CG_LT_GL_GL04_R17m=dict(sql="""
SELECT mean(value) AS CG_LT_GL_GL04_R17m   FROM "CG_LT_GL_GL04_17187WDPJ" where time > '{}' and time < '{}'
""", type="influxdb"),
    CG_LT_GL_GL04_Rluxin2=dict(sql="""
SELECT  mean(value)   AS CG_LT_GL_GL04_Rluxin2   FROM "CG"  WHERE code='CG_LT_GL_GL04_LDWDBG6200TE1141'  and time > '{}' and time < '{}'
""", type="influxdb")
)

rules = [{"upper": 999999.0, "unit": "t", "id": 1,
          "section": "{\"i0\": \"<30\", \"i1\": \"[30,58) \", \"i2\": \"[86,115)\", \"i3\": \"[86,115)\", \"i4\": \"[115,141)\", \"i5\": \"≥141\", \"i6\": None, \"s0\": 0, \"s1\": 0.2, \"s2\": 0.6, \"s3\": 0.6, \"s4\": 0.8, \"s5\": 1, \"s6\": None}",
          "name": "CG_LT_GL_GL04_Rliaopi", "type": "二级", "lower": 30.0, "desc": "日料批", "frequency": "天", "score": 5},
         {"upper": 570.0, "unit": "kg/t", "id": 2,
          "section": "{\"i0\": \"≤530\", \"i1\": \"(530,540] \", \"i2\": \"(550,560] \", \"i3\": \"(550,560] \", \"i4\": \"(560,570] \", \"i5\": \">570\", \"i6\": None, \"s0\": 1, \"s1\": 0.8, \"s2\": 0.4, \"s3\": 0.4, \"s4\": 0.2, \"s5\": 0, \"s6\": None}",
          "name": "CG_LT_GL_GL04_RRLB", "type": "一级", "lower": -999999.0, "desc": "燃料比", "frequency": "天", "score": 7},
         {"upper": 999999.0, "unit": "kg/t", "id": 3,
          "section": "{\"i0\": \"<120\", \"i1\": \"[120,125) \", \"i2\": \"[130,135)\", \"i3\": \"[130,135)\", \"i4\": \"[135,140)\", \"i5\": \"≥140\", \"i6\": None, \"s0\": 0, \"s1\": 0.2, \"s2\": 0.6, \"s3\": 0.6, \"s4\": 0.8, \"s5\": 1, \"s6\": None}",
          "name": "CG_LT_GL_GL04_Rcokerate", "type": "二级", "lower": 120.0, "desc": "煤比", "frequency": "天", "score": 5},
         {"upper": 999999.0, "unit": "m3/min", "id": 4,
          "section": "{\"i0\": \"<4600\", \"i1\": \"[4600,4800) \", \"i2\": \"[4900,5000)\", \"i3\": \"[4900,5000)\", \"i4\": \"[5000,5100)\", \"i5\": \"≥5100\", \"i6\": None, \"s0\": 0, \"s1\": 0.2, \"s2\": 0.6, \"s3\": 0.6, \"s4\": 0.8, \"s5\": 1, \"s6\": None}",
          "name": "CG_LT_GL_GL04_RLFLL", "type": "二级", "lower": 4600.0, "desc": "风量", "frequency": "天", "score": 3},
         {"upper": 999999.0, "unit": "m3/h", "id": 5,
          "section": "{\"i0\": \"<5000\", \"i1\": \"[5000,7000) \", \"i2\": \"[9000,10000)\", \"i3\": \"[9000,10000)\", \"i4\": \"[10000,11000)\", \"i5\": \"≥11000\", \"i6\": None, \"s0\": 0, \"s1\": 0.2, \"s2\": 0.6, \"s3\": 0.6, \"s4\": 0.8, \"s5\": 1, \"s6\": None}",
          "name": "CG_LT_GL_GL04_RFYLL", "type": "三级", "lower": 5000.0, "desc": "富氧流量", "frequency": "天", "score": 3},
         {"upper": 3.0, "unit": "次", "id": 6,
          "section": "{\"i0\": \"≤0\", \"i1\": \"(0,1] \", \"i2\": \"(2,3] \", \"i3\": \"(2,3] \", \"i4\": \">3\", \"i5\": None, \"i6\": None, \"s0\": 1, \"s1\": 0.8, \"s2\": 0.2, \"s3\": 0.2, \"s4\": 0, \"s5\": None, \"s6\": None}",
          "name": "CG_LT_GL_GL04_RjianfengCi", "type": "一级", "lower": -999999.0, "desc": "日减风次数", "frequency": "天",
          "score": 7}, {"upper": 999999.0, "unit": "%", "id": 7,
                        "section": "{\"i0\": \"<29\", \"i1\": \"[29,29.5) \", \"i2\": \"[30,30.5)\", \"i3\": \"[30,30.5)\", \"i4\": \"[30.5,31)\", \"i5\": \"≥31\", \"i6\": None, \"s0\": 0, \"s1\": 0.2, \"s2\": 0.6, \"s3\": 0.6, \"s4\": 0.8, \"s5\": 1, \"s6\": None}",
                        "name": "CG_LT_GL_GL04_RTQXZS", "type": "二级", "lower": 29.0, "desc": "透气性指数", "frequency": "天",
                        "score": 5}, {"upper": 26.0, "unit": "%", "id": 8,
                                      "section": "{\"i0\": \"≤14\", \"i1\": \"(14,17] \", \"i2\": \"(20,23]\", \"i3\": \"(20,23]\", \"i4\": \"(23,26]\", \"i5\": \">26\", \"i6\": None, \"s0\": 0.6, \"s1\": 0.8, \"s2\": 0.6, \"s3\": 0.6, \"s4\": 0.4, \"s5\": 0.2, \"s6\": None}",
                                      "name": "CG_LT_GL_GL04_RSBYCZB", "type": "三级", "lower": 14.0, "desc": "上部压差占比",
                                      "frequency": "天", "score": 3}, {"upper": 570.0, "unit": "%", "id": 9,
                                                                      "section": "{\"i0\": \"≤63\", \"i1\": \"(63,65] \", \"i2\": \"(66,68]\", \"i3\": \"(66,68]\", \"i4\": \"(68,70]\", \"i5\": \"(70,72]\", \"i6\": \">570\", \"s0\": 0, \"s1\": 0.2, \"s2\": 0.6, \"s3\": 0.6, \"s4\": 0.8, \"s5\": 1, \"s6\": 0.6}",
                                                                      "name": "CG_LT_GL_GL04_RXBYCZB", "type": "三级",
                                                                      "lower": 63.0, "desc": "下部压差占比", "frequency": "天",
                                                                      "score": 3},
         {"upper": 2550.0, "unit": "℃", "id": 10,
          "section": "{\"i0\": \"<2200\", \"i1\": \"[2200,2300) \", \"i2\": \"[2400,2500)\", \"i3\": \"[2400,2500)\", \"i4\": \"[2500,2550)\", \"i5\": \"≥2550\", \"i6\": None, \"s0\": 0, \"s1\": 0.2, \"s2\": 1, \"s3\": 1, \"s4\": 0.6, \"s5\": 0, \"s6\": None}",
          "name": "CG_LT_GL_GL04_RLLRSWD", "type": "三级", "lower": 2200.0, "desc": "理论燃烧温度", "frequency": "天",
          "score": 3}, {"upper": 999999.0, "unit": "kg·m/s", "id": 11,
                        "section": "{\"i0\": \"<10000\", \"i1\": \"[10000,10500) \", \"i2\": \"[11000,11500)\", \"i3\": \"[11000,11500)\", \"i4\": \"[11500,12000)\", \"i5\": \"≥12000\", \"i6\": None, \"s0\": 0, \"s1\": 0.2, \"s2\": 0.6, \"s3\": 0.6, \"s4\": 0.8, \"s5\": 1, \"s6\": None}",
                        "name": "CG_LT_GL_GL04_RGFDNKG", "type": "三级", "lower": 10000.0, "desc": "鼓风动能",
                        "frequency": "天", "score": 3}, {"upper": 210.0, "unit": "℃", "id": 12,
                                                        "section": "{\"i0\": \"≤150\", \"i1\": \"(150,170]\", \"i2\": \"(190,200]\", \"i3\": \"(190,200]\", \"i4\": \"(200,210]\", \"i5\": \">210\", \"i6\": None, \"s0\": 1, \"s1\": 0.8, \"s2\": 0.4, \"s3\": 0.4, \"s4\": 0.2, \"s5\": 0, \"s6\": None}",
                                                        "name": "CG_LT_GL_GL04_RLDWD", "type": "三级", "lower": -999999.0,
                                                        "desc": "炉顶温度", "frequency": "天", "score": 3},
         {"upper": 23000.0, "unit": None, "id": 13,
          "section": "{\"i0\": \"≤15000\", \"i1\": \"(15000,17000] \", \"i2\": \"(19000,21000] \", \"i3\": \"(19000,21000] \", \"i4\": \"(21000,23000] \", \"i5\": \">23000\", \"i6\": None, \"s0\": 1, \"s1\": 0.8, \"s2\": 0.4, \"s3\": 0.4, \"s4\": 0.2, \"s5\": 0, \"s6\": None}",
          "name": "CG_LT_GL_GL04_RRFH", "type": "三级", "lower": -999999.0, "desc": "热负荷", "frequency": "天", "score": 3},
         {"upper": 999999.0, "unit": "℃", "id": 14,
          "section": "{\"i0\": \"＜50\", \"i1\": \"[50,60)\", \"i2\": \"[70,80)\", \"i3\": \"[70,80)\", \"i4\": \"[80,90)\", \"i5\": \"≥90\", \"i6\": None, \"s0\": 0, \"s1\": 0.2, \"s2\": 0.6, \"s3\": 0.6, \"s4\": 0.8, \"s5\": 1, \"s6\": None}",
          "name": "CG_LT_GL_GL04_RFZWD", "type": "二级", "lower": 50.0, "desc": "阀座温度", "frequency": "天", "score": 5},
         {"upper": 3.0, "unit": "次", "id": 15,
          "section": "{\"i0\": \"＜1\", \"i1\": \"[1,2)\", \"i2\": \"≥3\", \"i3\": \"≥3\", \"i4\": None, \"i5\": None, \"i6\": None, \"s0\": 1, \"s1\": 0.6, \"s2\": 0, \"s3\": 0, \"s4\": None, \"s5\": None, \"s6\": None}",
          "name": "CG_LT_GL_GL04_RbengzuoguanCi", "type": "一级", "lower": -999999.0, "desc": "崩、坐料管道次数",
          "frequency": "天", "score": 7}, {"upper": 999999.0, "unit": "次", "id": 16,
                                          "section": "{\"i0\": \"＜10\", \"i1\": \"[10.12)\", \"i2\": \"[13,14)\", \"i3\": \"[13,14)\", \"i4\": \"≥14\", \"i5\": None, \"i6\": None, \"s0\": 0, \"s1\": 0.4, \"s2\": 0.8, \"s3\": 0.8, \"s4\": 1, \"s5\": None, \"s6\": None}",
                                          "name": "CG_LT_GL_GL04_RchutieCi", "type": "三级", "lower": 10.0,
                                          "desc": "日出铁次数", "frequency": "天", "score": 3},
         {"upper": 1500.0, "unit": "℃", "id": 17,
          "section": "{\"i0\": \"＜1440\", \"i1\": \"[1440,1450)\", \"i2\": \"[1460,1480]\", \"i3\": \"[1460,1480]\", \"i4\": \"(1480,1490]\", \"i5\": \"(1490,1500]\", \"i6\": \"＞1500\", \"s0\": 0, \"s1\": 0.2, \"s2\": 1, \"s3\": 1, \"s4\": 0.6, \"s5\": 0.2, \"s6\": 0}",
          "name": "CG_LT_GL_GL04_Rtswd", "type": "二级", "lower": 1440.0, "desc": "PT", "frequency": "天", "score": 5},
         {"upper": 0.55, "unit": "%", "id": 18,
          "section": "{\"i0\": \"＜0.1\", \"i1\": \"[0.1,0.15)\", \"i2\": \"[0.2,0.4]\", \"i3\": \"[0.2,0.4]\", \"i4\": \"(0.5,0.45]\", \"i5\": \"（0.5,0.55]\", \"i6\": \"＞0.55\", \"s0\": 0, \"s1\": 0.2, \"s2\": 1, \"s3\": 1, \"s4\": 0.6, \"s5\": 0.2, \"s6\": 0}",
          "name": "CG_LT_GL_GL04_RSi_Ti", "type": "三级", "lower": 0.1, "desc": "[Si+Ti]", "frequency": "天", "score": 3},
         {"upper": 999999.0, "unit": None, "id": 19,
          "section": "{\"i0\": \"≤0.55\", \"i1\": \"(0.55,0.6]\", \"i2\": \"(0.63,0.65]\", \"i3\": \"(0.63,0.65]\", \"i4\": \"(0.65,0.7]\", \"i5\": \"＞0.7\", \"i6\": None, \"s0\": 0, \"s1\": 0.2, \"s2\": 1, \"s3\": 1, \"s4\": 0.6, \"s5\": 0.4, \"s6\": None}",
          "name": "CG_LT_GL_GL04_RMg_Al", "type": "三级", "lower": 0.55, "desc": "MgO/Al2O3", "frequency": "天",
          "score": 3}, {"upper": 100.0, "unit": "℃", "id": 20,
                        "section": "{\"i0\": \"≤80\", \"i1\": \"(80,85]\", \"i2\": \"(90,95]\", \"i3\": \"(90,95]\", \"i4\": \"(95,100]\", \"i5\": \"＞100\", \"i6\": None, \"s0\": 1, \"s1\": 0.8, \"s2\": 0.4, \"s3\": 0.4, \"s4\": 0.2, \"s5\": 0, \"s6\": None}",
                        "name": "CG_LT_GL_GL04_R34m", "type": "三级", "lower": -999999.0, "desc": "34m", "frequency": "天",
                        "score": 3}, {"upper": 85.0, "unit": "℃", "id": 21,
                                      "section": "{\"i0\": \"≤65\", \"i1\": \"(65,70]\", \"i2\": \"(75,80]\", \"i3\": \"(75,80]\", \"i4\": \"(80,85]\", \"i5\": \"＞85\", \"i6\": None, \"s0\": 1, \"s1\": 0.8, \"s2\": 0.4, \"s3\": 0.4, \"s4\": 0.2, \"s5\": 0, \"s6\": None}",
                                      "name": "CG_LT_GL_GL04_R26m", "type": "三级", "lower": -999999.0, "desc": "26m",
                                      "frequency": "天", "score": 3}, {"upper": 110.0, "unit": "℃", "id": 22,
                                                                      "section": "{\"i0\": \"≤70\", \"i1\": \"(70,80]\", \"i2\": \"(90,100]\", \"i3\": \"(90,100]\", \"i4\": \"(100,110]\", \"i5\": \"＞110\", \"i6\": None, \"s0\": 1, \"s1\": 0.8, \"s2\": 0.4, \"s3\": 0.4, \"s4\": 0.2, \"s5\": 0, \"s6\": None}",
                                                                      "name": "CG_LT_GL_GL04_R24m", "type": "二级",
                                                                      "lower": -999999.0, "desc": "24m",
                                                                      "frequency": "天", "score": 5},
         {"upper": 65.0, "unit": "℃", "id": 23,
          "section": "{\"i0\": \"＜50\", \"i1\": \"[50,65]\", \"i2\": None, \"i3\": None, \"i4\": None, \"i5\": None, \"i6\": None, \"s0\": 0, \"s1\": 1, \"s2\": None, \"s3\": None, \"s4\": None, \"s5\": None, \"s6\": None}",
          "name": "CG_LT_GL_GL04_R17m", "type": "三级", "lower": 50.0, "desc": "17m", "frequency": "天", "score": 3},
         {"upper": 470.0, "unit": "℃", "id": 24,
          "section": "{\"i0\": \"[350,380)\", \"i1\": \"[380,410)\", \"i2\": \"[420,440)\", \"i3\": \"[420,440)\", \"i4\": \"[440,470)\", \"i5\": \"≥470\", \"i6\": None, \"s0\": 0.2, \"s1\": 0.4, \"s2\": 1, \"s3\": 1, \"s4\": 0.8, \"s5\": 0, \"s6\": None}",
          "name": "CG_LT_GL_GL04_Rluxin2", "type": "三级", "lower": -999999.0, "desc": "炉芯温度", "frequency": "天",
          "score": 3}]

if __name__ == "__main__":
    import pymysql
    from influxdb import InfluxDBClient
    import json

    conn = pymysql.Connect(
        host='10.8.0.3',  # 测试环境
        port=3306,
        user='root', passwd='BICI123456',
        db='cg', charset='utf8',
        cursorclass=pymysql.cursors.DictCursor)
    cursor = conn.cursor()

    influxdb_client = InfluxDBClient(host="10.8.0.3", port=8086, username='admin', password='BICI123456',
                                     database='bfbd2022')
    r = run_internal(cursor, influxdb_client, rules)
    print(r)
